package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by hanchao on 2018/1/17.
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService {

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String  upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename();
        //扩展名，
        //adb.jpg
        String fileExtensioName = fileName.substring(fileName.lastIndexOf("."));
        String uploadFileName  = UUID.randomUUID()+"."+fileExtensioName;
        logger.info("开始上传文件，上传的文件名:{}，上传的路径:{}, 新文件名：{}",fileName,path,uploadFileName);
        //文件目录
        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }

        File targetFile = new File(path,uploadFileName);
        try {
            file.transferTo(targetFile);
            //文件已经上传成功
            //TODO 将targetFile 上传到FTP服务器上

            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            //已经上传到FTP服务器上
            //TODO 上传后删除targetFile文件
            targetFile.delete();
        } catch (IOException e) {
            logger.error("文件上传异常",e);
        }
        return targetFile.getName();
    }
}
